// ============================================================================
// 错误处理初始化
// ============================================================================

import { errorHandler, ErrorCode, ErrorSeverity, createError } from './error-handler'
import { logger } from './logger'

// ============================================================================
// 全局错误处理初始化
// ============================================================================

export function initializeErrorHandling() {
  const appLogger = logger
  
  // 处理未捕获的Promise拒绝
  window.addEventListener('unhandledrejection', (event) => {
    const error = createError(
      ErrorCode.UNKNOWN_ERROR,
      `Unhandled promise rejection: ${event.reason}`,
      ErrorSeverity.HIGH,
      {
        component: 'Global',
        action: 'unhandledrejection'
      }
    )

    errorHandler.handle(error)
    
    // 阻止默认的控制台错误输出
    event.preventDefault()
  })

  // 处理未捕获的JavaScript错误
  window.addEventListener('error', (event) => {
    const error = createError(
      ErrorCode.INTERNAL_ERROR,
      event.message || 'Unknown error',
      ErrorSeverity.HIGH,
      {
        component: 'Global',
        action: 'error',
        metadata: {
          filename: event.filename,
          lineno: event.lineno,
          colno: event.colno
        }
      }
    )

    errorHandler.handle(error)
  })

  // 处理资源加载错误
  window.addEventListener('error', (event) => {
    if (event.target && event.target !== window) {
      const target = event.target as HTMLElement
      const error = createError(
        ErrorCode.FILE_ERROR,
        `Resource loading failed: ${target.tagName}`,
        ErrorSeverity.MEDIUM,
        {
          component: 'Global',
          action: 'resource-error',
          metadata: {
            tagName: target.tagName,
            src: (target as any).src || (target as any).href
          }
        }
      )

      errorHandler.handle(error)
    }
  }, true) // 使用捕获阶段

  // 添加错误监听器用于通知
  errorHandler.addErrorListener((error) => {
    // 根据错误严重程度决定是否显示通知
    if (error.severity === ErrorSeverity.CRITICAL || error.severity === ErrorSeverity.HIGH) {
      // 这里可以集成通知系统
      console.error('Critical/High severity error:', error)
    }
  })

  appLogger.info('Error handling initialized')
}

// ============================================================================
// 网络错误处理
// ============================================================================

export function handleNetworkError(error: Error, context?: { url?: string; method?: string }) {
  const networkError = createError(
    ErrorCode.NETWORK_ERROR,
    `Network request failed: ${error.message}`,
    ErrorSeverity.MEDIUM,
    {
      component: 'Network',
      action: context?.method || 'request',
      metadata: {
        url: context?.url
      }
    },
    true // 网络错误通常可重试
  )

  return errorHandler.handle(networkError)
}

// ============================================================================
// API错误处理
// ============================================================================

export function handleAPIError(response: Response, context?: { url?: string; method?: string }) {
  let errorCode: ErrorCode
  let severity: ErrorSeverity

  switch (response.status) {
    case 401:
      errorCode = ErrorCode.AUTH_FAILED
      severity = ErrorSeverity.HIGH
      break
    case 403:
      errorCode = ErrorCode.PERMISSION_DENIED
      severity = ErrorSeverity.HIGH
      break
    case 404:
      errorCode = ErrorCode.DATA_NOT_FOUND
      severity = ErrorSeverity.MEDIUM
      break
    case 429:
      errorCode = ErrorCode.RATE_LIMITED
      severity = ErrorSeverity.MEDIUM
      break
    case 500:
    case 502:
    case 503:
    case 504:
      errorCode = ErrorCode.INTERNAL_ERROR
      severity = ErrorSeverity.HIGH
      break
    default:
      errorCode = ErrorCode.UNKNOWN_ERROR
      severity = ErrorSeverity.MEDIUM
  }

  const apiError = createError(
    errorCode,
    `API request failed: ${response.status} ${response.statusText}`,
    severity,
    {
      component: 'API',
      action: context?.method || 'request',
      metadata: {
        url: context?.url,
        status: response.status,
        statusText: response.statusText
      }
    },
    errorCode === ErrorCode.RATE_LIMITED || response.status >= 500
  )

  return errorHandler.handle(apiError)
}

// ============================================================================
// 验证错误处理
// ============================================================================

export function handleValidationError(errors: Record<string, string[]>, context?: { form?: string }) {
  const validationError = createError(
    ErrorCode.VALIDATION_ERROR,
    'Form validation failed',
    ErrorSeverity.LOW,
    {
      component: 'Validation',
      action: 'validate',
      metadata: {
        form: context?.form,
        errors
      }
    }
  )

  return errorHandler.handle(validationError)
}

// ============================================================================
// 任务错误处理
// ============================================================================

export function handleTaskError(error: Error, taskId: string, context?: { type?: string; step?: string }) {
  const taskError = createError(
    ErrorCode.TASK_FAILED,
    `Task failed: ${error.message}`,
    ErrorSeverity.HIGH,
    {
      component: 'Task',
      action: context?.step || 'execute',
      taskId,
      metadata: {
        type: context?.type
      }
    },
    true // 任务错误通常可重试
  )

  return errorHandler.handle(taskError)
}

// ============================================================================
// 账号错误处理
// ============================================================================

export function handleAccountError(error: Error, accountId: string, context?: { action?: string }) {
  const accountError = createError(
    ErrorCode.ACCOUNT_INVALID,
    `Account error: ${error.message}`,
    ErrorSeverity.HIGH,
    {
      component: 'Account',
      action: context?.action || 'validate',
      accountId
    }
  )

  return errorHandler.handle(accountError)
}

// ============================================================================
// 错误恢复策略
// ============================================================================

export class ErrorRecoveryStrategy {
  private static retryAttempts = new Map<string, number>()
  private static readonly MAX_RETRIES = 3
  private static readonly RETRY_DELAY = 1000

  static async withRetry<T>(
    operation: () => Promise<T>,
    context: { component: string; action: string },
    maxRetries: number = this.MAX_RETRIES
  ): Promise<T> {
    const key = `${context.component}:${context.action}`
    let attempts = this.retryAttempts.get(key) || 0

    try {
      const result = await operation()
      // 成功后重置重试计数
      this.retryAttempts.delete(key)
      return result
    } catch (error) {
      attempts++
      this.retryAttempts.set(key, attempts)

      const appError = errorHandler.handle(error as Error, context)

      if (appError.retryable && attempts < maxRetries) {
        logger.warn(`Retrying operation ${key}, attempt ${attempts}/${maxRetries}`)
        
        // 指数退避延迟
        await new Promise(resolve => 
          setTimeout(resolve, this.RETRY_DELAY * Math.pow(2, attempts - 1))
        )
        
        return this.withRetry(operation, context, maxRetries)
      }

      throw appError
    }
  }

  static resetRetryCount(component: string, action: string) {
    const key = `${component}:${action}`
    this.retryAttempts.delete(key)
  }

  static getRetryCount(component: string, action: string): number {
    const key = `${component}:${action}`
    return this.retryAttempts.get(key) || 0
  }
}

// ============================================================================
// 错误报告
// ============================================================================

export interface ErrorReport {
  errorId: string
  timestamp: string
  userAgent: string
  url: string
  userId?: string
  sessionId?: string
  error: {
    code: string
    message: string
    severity: string
    stack?: string
    context?: any
  }
  systemInfo: {
    platform: string
    language: string
    timezone: string
    screenResolution: string
    memory?: any
  }
}

export function generateErrorReport(error: any): ErrorReport {
  return {
    errorId: `error_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`,
    timestamp: new Date().toISOString(),
    userAgent: navigator.userAgent,
    url: window.location.href,
    error: {
      code: error.code || 'UNKNOWN_ERROR',
      message: error.message,
      severity: error.severity || 'MEDIUM',
      stack: error.stack,
      context: error.context
    },
    systemInfo: {
      platform: navigator.platform,
      language: navigator.language,
      timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
      screenResolution: `${screen.width}x${screen.height}`,
      memory: (performance as any).memory ? {
        used: (performance as any).memory.usedJSHeapSize,
        total: (performance as any).memory.totalJSHeapSize,
        limit: (performance as any).memory.jsHeapSizeLimit
      } : undefined
    }
  }
}
